package com.example.demo.util;

public class UnderlineToCamelCaseUtil {

    /**
     * 将下划线风格的字符串转换为驼峰风格字符串（首字母小写）
     * 例如："user_name" 转换为 "userName"
     *
     * @param underlineStr 下划线风格的字符串
     * @return 转换后的驼峰风格字符串
     */
    public static String underlineToCamelCase(String underlineStr) {
        if (underlineStr == null || underlineStr.isEmpty()) {
            return underlineStr;
        }
        StringBuilder result = new StringBuilder();
        String[] words = underlineStr.split("_");
        for (int i = 0; i < words.length; i++) {
            if (i == 0) {
                result.append(words[0].toLowerCase());
            } else {
                result.append(capitalize(words[i].toLowerCase()));
            }
        }
        return result.toString();
    }

    /**
     * 将下划线风格的字符串转换为驼峰风格字符串（首字母大写）
     * 例如："user_name" 转换为 "UserName"
     *
     * @param underlineStr 下划线风格的字符串
     * @return 转换后的驼峰风格字符串
     */
    public static String underlineToCamelCaseWithFirstUpper(String underlineStr) {
        if (underlineStr == null || underlineStr.isEmpty()) {
            return underlineStr;
        }
        StringBuilder result = new StringBuilder();
        String[] words = underlineStr.split("_");
        for (int i = 0; i < words.length; i++) {
            result.append(capitalize(words[i].toLowerCase()));
        }
        return result.toString();
    }

    /**
     * 将字符串的首字母转换为大写
     *
     * @param word 要转换的字符串
     * @return 首字母大写后的字符串
     */
    private static String capitalize(String word) {
        if (word == null || word.isEmpty()) {
            return word;
        }
        return word.substring(0, 1).toUpperCase() + word.substring(1);
    }

    public static void main(String[] args) {
        String underlineStr = "user_name";
        System.out.println("首字母小写的驼峰转换结果: " + underlineToCamelCase(underlineStr));
        System.out.println("首字母大写的驼峰转换结果: " + underlineToCamelCaseWithFirstUpper(underlineStr));
    }
}